#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import argparse
from PIL import Image
from reportlab.lib.pagesizes import letter, A4
from reportlab.pdfgen import canvas

def get_image_files(directory):
    """获取指定目录下的所有图片文件"""
    image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff']
    image_files = []
    
    if os.path.exists(directory):
        for file in os.listdir(directory):
            file_path = os.path.join(directory, file)
            if os.path.isfile(file_path):
                ext = os.path.splitext(file)[1].lower()
                if ext in image_extensions:
                    image_files.append(file_path)
    
    # 按文件名排序
    image_files.sort()
    return image_files

def create_pdf(image_files, output_pdf, page_size='A4'):
    """将图片文件转换为PDF"""
    if not image_files:
        print("没有找到图片文件")
        return False
    
    # 选择页面大小
    if page_size.upper() == 'A4':
        pdf_size = A4
    else:
        pdf_size = letter
    
    c = canvas.Canvas(output_pdf, pagesize=pdf_size)
    width, height = pdf_size
    
    for img_path in image_files:
        try:
            img = Image.open(img_path)
            img_width, img_height = img.size
            
            # 计算缩放比例，使图片适应页面
            ratio = min(width / img_width, height / img_height)
            new_width = img_width * ratio
            new_height = img_height * ratio
            
            # 计算居中位置
            x = (width - new_width) / 2
            y = (height - new_height) / 2
            
            # 在PDF中绘制图片
            c.drawImage(img_path, x, y, new_width, new_height)
            c.showPage()  # 添加新页面
            
            print(f"已添加: {os.path.basename(img_path)}")
        except Exception as e:
            print(f"处理图片 {img_path} 时出错: {e}")
    
    c.save()
    print(f"PDF已保存为: {output_pdf}")
    return True

def main():
    parser = argparse.ArgumentParser(description='将图片转换为PDF文件')
    parser.add_argument('-i', '--input', default='images', help='输入图片目录 (默认: images)')
    parser.add_argument('-o', '--output', default='output.pdf', help='输出PDF文件名 (默认: output.pdf)')
    parser.add_argument('-s', '--size', default='A4', choices=['A4', 'letter'], help='PDF页面大小 (默认: A4)')
    
    args = parser.parse_args()
    
    # 获取图片文件
    image_files = get_image_files(args.input)
    
    if not image_files:
        print(f"在目录 '{args.input}' 中没有找到图片文件")
        return
    
    print(f"找到 {len(image_files)} 个图片文件")
    
    # 创建PDF
    create_pdf(image_files, args.output, args.size)

if __name__ == "__main__":
    main()